//
//  ModifyUserInfoVC.m
//  TuYouAPP
//
//  Created by L on 14-2-25.
//
//

#import "ModifyUserInfoVC.h"
#import "UIImageView+WebCache.h"
#import "VPImageCropperViewController.h"
#define ORIGINAL_MAX_WIDTH 640
@interface ModifyUserInfoVC ()<VPImageCropperDelegate>
{
    TSLocateView *locateView;
    BOOL pickerIsShow;
    BOOL HaveImage;
}

@end

@implementation ModifyUserInfoVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (IBAction)chooseHead:(id)sender {
    [locateView cancelView];

    [self.userName resignFirstResponder];
    [self.userSign resignFirstResponder];
    [self.userAge resignFirstResponder];
    UIActionSheet *ac = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册中选择", nil];
    ac.tag = 1001;
    [ac showInView:[self.view window]];
}
- (IBAction)chooseSex:(id)sender {
    [locateView cancelView];

    [self.userName resignFirstResponder];
    [self.userSign resignFirstResponder];
    [self.userAge resignFirstResponder];
    
        UIActionSheet *ac = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"男",@"女", nil];
    ac.tag = 1002;
    [ac showInView:[self.view window]];

}

- (IBAction)chooseAddr:(id)sender {
    [self.userName resignFirstResponder];
    [self.userSign resignFirstResponder];
    [self.userAge resignFirstResponder];
    if (!pickerIsShow) {
        [self showLocateView];
        pickerIsShow = YES;
        
    }

    
}
-(void)didCancelPicker
{
    pickerIsShow = NO;
}
-(void)didSelectPicker:(TSLocateView *)selectView
{
    pickerIsShow = NO;

    NSMutableString *str = [[NSMutableString alloc]init];
    [str appendString:selectView.locate.state];
    [str appendString:@","];
    [str appendString:selectView.locate.city];
    self.userAddr.text = str;
    
}
- (void)showLocateView {
    //[self resignAll];
    locateView = [[TSLocateView alloc] initWithTitle:@"选择城市" delegate:self];
    locateView.pickerDelegate = self;
    [locateView showInView:self.view];
}
- (void)viewDidLoad
{
    self.mPageName = @"修改资料";
    [super viewDidLoad];
    pickerIsShow = NO;
    HaveImage = NO;
    self.Title = @"修改资料";
    self.LeftBarTitle = @"我的";
    self.RightBarTitle = @"保存";
    // Do any additional setup after loading the view from its nib.
    self.topview.layer.borderWidth = 0.5;
    self.topview.layer.borderColor = [ColorRGB(212, 212, 212)CGColor];

    self.midview.layer.borderWidth = 0.5;
    self.midview.layer.borderColor = [ColorRGB(212, 212, 212)CGColor];
    self.botView.layer.borderWidth = 0.5;
    self.botView.layer.borderColor = [ColorRGB(212, 212, 212)CGColor];
    [self.myView setContentSize: CGSizeMake(320, 300)];
    self.userAge.delegate = self;
    self.userSign.delegate = self;
    self.userName.delegate = self;
    self.userName.text = [TYUser currentUser].mUserDisplayName;
    //self.userAddr.text = [AVu]
    self.userAge.text = [TYUser currentUser].mAge;
    self.userduijiang.text = [TYUser currentUser].mDuijiang;
    self.userAddr.text = [TYUser currentUser].mUserPointAddr;
    self.userSign.text = [TYUser currentUser].mUserSign;
    [self.headImage setImageWithURL:[NSURL URLWithString:[TYUser currentUser].mHeadImgURL] placeholderImage:[UIImage imageNamed:@"70_70.png"]];
    
    
}
-(void)textViewDidBeginEditing:(UITextView *)textView {
    [locateView cancelView];

}
-(void)textFieldDidBeginEditing:(UITextField *)textField {
    [locateView cancelView];

}
-(void)leftBtnTouched:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)rightBtnTouched:(id)sender
{
    if (self.userName.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"姓名不能为空"];
        return;
    }
    [SVProgressHUD showWithStatus:@"修改中"];
    [[TYUser currentUser]modifyUserinfoSex:self.userSex.text  headImage:HaveImage?self.headImage.image:nil name:self.userName.text addr:self.userAddr.text sign:self.userSign.text age:[self.userAge.text intValue] duijiang:self.userduijiang.text callback:^(NSString *eror) {
       // [SVProgressHUD dismiss];
        if (!eror) {
            [SVProgressHUD showSuccessWithStatus:@"修改成功"];
            [TYUser updateUser];
            [self.navigationController popViewControllerAnimated:YES];

        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"修改失败"];
        }
    }];
}


#pragma mark -
#pragma mark UIActionSheet && UIAlertView Delegate

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 1001) {
        if (buttonIndex != 2) {
            
            [self startImagePickerVCwithButtonIndex:buttonIndex];
            
        }
    }
    else
    {
        if (buttonIndex == 0) {
            self.userSex.text = @"男";
        }
        else
        {
            self.userSex.text = @"女";
        }
    }
   
    
}

- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    self.headImage .image  = editedImage;
    HaveImage = YES;
    NSLog(@"image %F,%F",editedImage.size.width,editedImage.size.height);
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

- (void)startImagePickerVCwithButtonIndex:(NSInteger )buttonIndex
{
    
    int type;
    if (buttonIndex == 0) {
        type = UIImagePickerControllerSourceTypeCamera;
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = type;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagePicker.allowsEditing = YES;
        
        [self presentViewController:imagePicker animated:YES completion:^{
            
        }];
        
    }
    else if(buttonIndex == 1){
        QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = NO;
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
        [self presentViewController:navigationController animated:YES completion:NULL];
        
        
    }
    
    
    
}
- (void)imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingMediaWithInfo:(id)info
{
    
    //   static BOOL isAddFrame = NO;
    [imagePickerController dismissViewControllerAnimated:YES completion:^() {
    UIImage *tempImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    tempImage =  [self imageByScalingToMaxSize:tempImage];
    
    
    //  [self dismissViewControllerAnimated:YES completion:NULL];
    VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:tempImage cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:5.0];
    imgEditorVC.delegate = self;
    [self presentViewController:imgEditorVC animated:YES completion:^{
        // TO DO
    }];
    }];
    
}
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}


- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
